<template>
  <div class="login">
    <van-nav-bar left-text="" left-arrow @click-left="onClickLeft">
      <template #title>
        <div
          class="title iconfont"
          :class="isLogin ? 'icon-denglu' : 'icon-zhuce'"
        ></div>
      </template>
    </van-nav-bar>
    <div class="logo">
      <div class="img">
        <img src="../../assets/img/head_img/logo.png" alt="" />
      </div>
      <div class="text">
        <span class="chinese">暮雪商城</span><br />
        <span class="english">Twilight Snow Mall</span>
      </div>
    </div>
    <div class="login_model">
      <div class="useLogin" v-if="isLogin">
        <!-- 输入手机号，调起手机号键盘 -->
        <van-field
          v-model.trim="loginPhone"
          type="tel"
          label="手 机 号:"
          placeholder="请输入11位手机号码"
          @blur="loginVertel"
        />
        <!-- 允许输入正整数，调起纯数字键盘 -->
        <van-field
          v-model.trim="loginPassword"
          type="password"
          label="密 　 码:"
          placeholder="请输入6-15位有效密码"
          @blur="loginVertel"
          v-if="isMsgLogin"
        />
        <van-field
          v-model.trim="sms"
          center
          clearable
          label="验 证 码:"
          placeholder="请输入短信验证码"
          v-else
        >
          <template #button>
            <van-button
              size="small"
              type="primary"
              @click="setCode"
              v-if="!timer"
              >{{ times ? "重新发送" : "发送验证码" }}</van-button
            >
            <van-button size="small" type="primary" v-else
              >{{ resendTime }}s后重新发送</van-button
            >
          </template>
        </van-field>

        <div class="loginBot">
          <span @click="isLogin = !isLogin">用户注册</span>
          <span @click="isMsgLogin = !isMsgLogin">{{
            isMsgLogin ? "验证码登录" : "密码登录"
          }}</span>
          <span>忘记密码</span>
        </div>
      </div>
      <div class="useRegister" v-else>
        <!-- 输入手机号，调起手机号键盘 -->
        <van-field
          v-model.trim="regPhone"
          type="tel"
          label="手 机 号:"
          placeholder="请输入11位手机号码"
          @blur="regvertel"
        />
        <!-- 允许输入正整数，调起纯数字键盘 -->
        <van-field
          v-model.trim="regPassword"
          type="password"
          label="密 　 码:"
          placeholder="请输入6-15位有效密码"
          @blur="resverpwd"
        />
        <van-field
          v-model.trim="sureRegPassword"
          type="password"
          label="确认密码:"
          placeholder="两次密码需保持一致"
          @blur="check"
        />
        <van-field
          v-model.trim="sms"
          center
          clearable
          label="验 证 码:"
          placeholder="请输入短信验证码"
        >
          <template #button>
            <van-button
              size="small"
              type="primary"
              @click="setCode"
              v-if="!timer"
              >{{ times ? "重新发送" : "发送验证码" }}</van-button
            >
            <van-button size="small" type="primary" v-else
              >{{ resendTime }}s后重新发送</van-button
            >
          </template>
        </van-field>
        <div class="registerBot">
          <span @click="isLogin = !isLogin"
            ><u>已有账户?<b>去登录</b></u></span
          >
        </div>
      </div>
      <div class="btn">
        <van-button type="primary" @click="toUser">{{
          isLogin ? "登 　 录" : "注 　 册"
        }}</van-button>
      </div>
    </div>
    <div class="file" v-if="isLogin">
      <div
        :class="isAgree ? 'icon-xuanzhongduigou' : 'icon-weixuanzhong'"
        class="icon iconfont"
        @click="isAgree = !isAgree"
      ></div>
      <div>
        我已阅读并同意 <span @click="toAgreement">《用户协议》</span>与
        <span @click="toPrivacy">《隐私条款》</span>
      </div>
    </div>
  </div>
</template>

<script>
import { Toast, Dialog } from "vant";
import {
  sendMsgApi,
  reqMsgLoginApi,
  reqPwdLoginApi,
  registerApi,
} from "@/services";
import { setStorage } from "@/utils/storage";
//引入辅助函数：mapState映射
import { mapState, mapMutations, mapGetters } from "vuex";
export default {
  name: "logion",
  data() {
    return {
      timer: null,
      resendTime: 30,
      isLogin: true,
      loginPhone: "",
      loginPassword: "",
      sureRegPassword: "",
      regPassword: "",
      regPhone: "",
      radio: "1",
      sms: "",
      isMsgLogin: true,
      isAgree: false,
      times: 0,
      isSee: false,
    };
  },
  computed: mapGetters(["login"]),
  methods: {
    ...mapMutations(["initUser"]),
    ...mapMutations(["logout"]),
    async setLogionreq() {
      if (this.isMsgLogin) {
        var res = await reqPwdLoginApi(this.loginPhone, this.loginPassword);
        var text = "账号或密码错误";
      } else {
        var res = await reqMsgLoginApi(this.loginPhone, this.sms);
        var text = "验证码错误";
      }
      if (res.code == 200) {
        Toast.success("登录成功");
        //1,将数据保存到本地
        setStorage("user", res.data);
        //2，将数据集成到vuex中，方便其他组件获取登录状态
        //方式1：
        // this.$store.commit("initUser");
        //方式2：
        this.initUser();
        this.$router.back();
        return;
      }
      Toast.fail(text);
    },
    onClickLeft() {
      this.$router.back();
    },
    useisAgree() {
      if (!this.isAgree) {
        Toast("请阅读并勾选协议");
        return false;
      }
      return true;
    },
    loginVertel() {
      if (!this.loginPhone) return false;

      const loginFlag = /^1[3|5|6|7|8|9]\d{9}$/.test(this.loginPhone);

      if (!loginFlag) {
        // console.log(123);
        Toast("手机号码格式不正确");
        return false;
      }
      return true;
    },
    loginverpwd() {
      if (!this.loginPassword) return false;
      if (this.loginPassword.length < 6) {
        Toast("密码长度少于六位");
        return false;
      } else if (this.loginPassword.length > 15) {
        Toast("密码长度大于15位");
        return false;
      }
      return true;
    },
    regvertel() {
      if (!this.regPhone) return false;
      const regFlag = /^1[3|5|6|7|8|9]\d{9}$/.test(this.regPhone);
      if (!regFlag) {
        Toast("手机号码格式不正确");
        return false;
      }
      return true;
    },
    resverpwd() {
      if (!this.regPassword) return false;
      if (this.regPassword.length < 6) {
        Toast("密码长度少于六位");
        return false;
      } else if (this.regPassword.length > 15) {
        Toast("密码长度大于15位");
        return false;
      }
      return true;
    },
    check() {
      if (!this.sureRegPassword) return false;
      if (this.sureRegPassword != this.regPassword) {
        Toast("两次密码不一致");
        return false;
      }
      return true;
    },
    //发送验证码
    setCode() {
      this.sms = "";
      if (!this.useisAgree()) {
        return;
      } else if (this.isLogin) {
        if (!this.loginVertel()) {
          return;
        }
      } else {
        if (!this.regvertel()) {
          return;
        }
      }
      this.nextSetMsg();
    },
    //重新发送定时器
    async nextSetMsg() {
      this.times++;
      if (this.times > 3) {
        Toast.fail("验证码请求次数过多");
        return;
      }
      this.timer = setInterval(() => {
        this.resendTime--;
        if (this.resendTime == 0) {
          clearInterval(this.timer);
          this.timer = null;
          this.resendTime = 30;
          return;
        }
      }, 1000);
      if (this.isLogin) {
        await sendMsgApi(this.loginPhone);
      } else {
        await sendMsgApi(this.regPhone);
      }
    },
    //验证码格式验证
    checkCode() {
      if (!/^\d{6}$/.test(this.sms)) {
        Toast.fail("验证码格式不正确");
        return false;
      }
      return true;
    },
    //登录
    Login() {
      if (!this.loginVertel()) {
        return;
      } else if (!this.useisAgree()) {
        return;
      }
      if (this.isMsgLogin) {
        if (!this.loginverpwd()) {
          return;
        }
      } else {
        if (!this.times) {
          Toast.fail("验证码未发送");
          return;
        } else if (!this.checkCode()) {
          return;
        }
      }
      this.setLogionreq();
    },
    //注册
    register() {
      if (!this.regvertel()) {
        // console.log(1);
        return;
      } else if (!this.resverpwd()) {
        // console.log(2);
        return;
      } else if (!this.check()) {
        // console.log(123);
        return;
      } else if (!this.times) {
        Toast.fail("验证码未发送");
        return;
      } else if (!this.checkCode()) {
        return;
      }
      this.toRegister();
    },
    toUser() {
      if (this.isLogin) {
        this.Login();
      } else {
        this.register();
      }
    },
    async toRegister() {
      const res = await registerApi(this.regPhone, this.regPassword, this.sms);
      console.log(res);
      if (res.code == 200) {
        Toast.success("恭喜你，注册成功");
        this.isLogin = true;
        return;
      } else if (res.code == 409) {
        Toast.fail("账号已存在");
        return;
      } else {
        Toast.fail("验证码有误或密码不符合格式");
        return;
      }
    },
    toAgreement() {
      this.$router.push("https://www.baidu.com/s?wd=用户协议");
    },
    toPrivacy() {
      this.$router.push("https://www.baidu.com/s?wd=隐私条款");
    },
  },
  destroyed() {
    Dialog.close();
  },
  beforeRouteEnter(to, from, next) {
    next(function (that) {
      // console.log(that);

      if (that.login) {
        Dialog.confirm({
          title: "温馨提示",
          message: "您已经登录了账号，是否需要退出登录？",
          closeOnPopstate: false,
        })
          .then(() => {
            that.logout();
            Toast.success("退出成功");
          })
          .catch(() => {
            that.$router.back("/");
          });
      }
    });
  },
};
</script>

<style lang="less" scoped>
.login {
  .title {
    font-size: 40px;
  }
  .van-nav-bar {
    background-color: #08dbdb;

    /deep/.van-icon {
      color: #fff;
    }
    /deep/.van-nav-bar__title {
      color: #fff;
    }
  }
  .logo {
    width: 100%;
    height: 292px;
    padding: 0 40px;
    box-sizing: border-box;
    background: linear-gradient(#08dbdb 30%, #c3dbe0);
    display: flex;
    justify-content: center;
    align-items: center;
    .img {
      width: 129px;
      height: 111px;
      // border: #fff solid 1px;
      img {
        width: 100%;
        height: 100%;
      }
    }
    .text {
      margin-left: 10px;
      color: #fff;
      .chinese {
        font-size: 65px;
        line-height: 80px;
        font-weight: 700;
        font-family: "行楷体", "Hannotate SC", cursive;
      }
      .english {
        font-size: 25px;
        font-weight: 600;
        line-height: 38px;
        letter-spacing: 2px;
        font-family: "Comic Sans MS", cursive;
      }
    }
  }
  .login_model {
    width: 580px;
    margin: 0 auto;
    margin-top: 30px;
    .van-cell {
      background-color: #fbfafa;
      width: 100%;
      padding: 15px 0;
    }
    /deep/.van-field__label {
      font-size: 32px;
      width: auto;
    }

    .van-button {
      background-color: #08dbdb;
    }
    .loginBot {
      display: flex;
      justify-content: space-between;
      color: #666;
      font-size: 28px;
      margin-top: 30px;
    }
    .registerBot {
      display: flex;
      justify-content: center;
      color: #666;
      font-size: 28px;
      margin-top: 30px;
      b {
        font-weight: normal;
        color: blue;
      }
    }
  }
  .btn {
    /deep/.van-button {
      width: 580px;
      margin-top: 30px;
      background-color: #08dbdb;
      border-color: #08dbdb;
      padding: 0 10px;
      font-size: 35px;
    }
  }
  .file {
    display: flex;
    font-size: 28px;
    width: 580px;
    margin: 0 auto;
    margin-top: 30px;
    color: #666;
    span {
      color: #08dbdb;
    }
    div {
      margin-right: 10px;
    }
  }
}
</style>
